import io
import pathlib
import json
import logging.config
import click

@click.group()
@click.option("--debug", is_flag=True)
@click.option(
    "--config", "config_path",
    default=pathlib.Path(__file__).parent.parent/"config.json",
    envvar="CONFIGPATH",
    type=click.Path(exists=True, dir_okay=False),
)
@click.pass_context
def root(ctx, config_path, debug):
    with open(config_path, encoding="utf-8") as f:
        config = json.load(f)
    ctx.obj = {"config": config}
    config_logging(debug)


def config_logging(debug=False):
    handlers = ['file']
    if debug:
        handlers.append('console')
    logging.config.dictConfig({
        "version": 1,
        "formatters": {
            "fmt1": {"format": '[%(asctime)s][%(levelname)s] %(message)s'},
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "formatter": "fmt1"
            },
            "file": {
                "class": "logging.handlers.TimedRotatingFileHandler",
                "formatter": "fmt1",
                "filename": pathlib.Path(__file__).parent.parent/"logs"/"error.log",
                "when": "W0",
                "encoding": "utf-8"
            }
        },
        "loggers": {
            "stock_watcher": {
                "handlers": handlers,
                "level": 'INFO'
            }
        }
    })
